package com.thread.atomic;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author wangyingjie
 * @date
 * @remark 原子操作辅助类
 */
public class AtomicDemo {

    public static class Candidate{
        int id;
        volatile int score;

    }

    /**
     * 将score字段变为原子操作，字段不能是private
     */
    static AtomicIntegerFieldUpdater<Candidate> scoreUpdate = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        Candidate candidate = new Candidate();
        Thread[] threads = new Thread[1000];
        for (int i = 0; i < 1000; i++) {
            threads[i] = new Thread(){
                @Override
                public void run() {
                    if (Math.random()>0.4){
                        atomicInteger.incrementAndGet();
                        scoreUpdate.incrementAndGet(candidate);
                    }
                }
            };
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            Thread thread = threads[i];
            thread.join();
        }

        System.out.println(candidate.score);
        System.out.println(atomicInteger.get());
    }

}
